package com.sise.service;

import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class AidlClient extends Activity {

    private ICaculate calculateService;
    private Button get;
    EditText editText_A, editText_B, result;
    private ServiceConnection conn = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        conn= new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                // 获取远程Service的onBind方法返回的对象的代理
                calculateService =ICaculate.Stub.asInterface(service);
            }
            @Override
            public void onServiceDisconnected(ComponentName name) {
                System.out.println("disconnected!!!!");
                calculateService=null;
            }
        };

        get=(Button) findViewById(R.id.button_get);
        editText_A=(EditText) findViewById(R.id.editText_A);
        editText_B=(EditText) findViewById(R.id.editText_B);
        result=(EditText) findViewById(R.id.result);

        // 创建所需绑定服务的Intent
        Intent intent = new Intent();
        intent.setAction("org.sise.aidl.action.AIDL_SERVICE");
        intent.setPackage(getPackageName());

        // 通过bindService绑定远程服务，使用Service.BIND_AUTO_CREATE标志位
        bindService(intent,conn,Service.BIND_AUTO_CREATE);
        get.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // 获取、并显示远程Service的状态
                int a = Integer.valueOf(editText_A.getText().toString());
                int b = Integer.valueOf(editText_B.getText().toString());
                // 调用calculateService计算a+b的结果
                int ret = 0;
                try {
                    ret = calculateService.add(a,b);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                result.setText(String.valueOf(ret));
            }
        });
    }
}